package command;

import java.util.Date;
import java.util.List;

import model.impl.ScheduleImpl;
import model.impl.Station;
import DTO.DTOManager;
import DTO.ScheduleDTO;
import DTO.StationDTO;

import com.gmail.at.vssabinin.train_transport_system_part1.Protocol;
import com.gmail.at.vssabinin.train_transport_system_part1.ReceivedData;


/**
 * Class represents command interface;
 * It sends all the schedules objects to the client user. To send them 
 * it uses DTO. If there is any schedules according to requirements given
 * by user it sends message OK and the list of schedules, else sends no 
 * and null.
 */
public class ClientGetDepartureSchedule implements Command {

	private Protocol protocol = new Protocol();
	
	@Override
	public void execute(ReceivedData recived) {
		model.Schedule scheduleImpl = new ScheduleImpl();
		Protocol.Message message = this.protocol.decodeMessage(recived.data);
		StationDTO stationDTO = (StationDTO) message.getObject();
		Station station = (new DTOManager()).createNewStationFromDTO(stationDTO);
		List<ScheduleDTO> schedulesDTO = scheduleImpl.getStationDeparturelSchedule(station);
		if (schedulesDTO != null){
			Date currentDate = new Date();
			for (int i = 0; i < schedulesDTO.size(); i++) {
				if (schedulesDTO.get(i).getDateOfDeparture().compareTo(currentDate) < 0 ){
					schedulesDTO.remove(i);
				}
			}
			if (schedulesDTO.isEmpty()) {
				Protocol.Message answer = this.protocol.new Message("no", null);
				recived.server.send(recived.socket, this.protocol.createMessage(answer));
			} else {
				Protocol.Message answer = this.protocol.new Message("ok", schedulesDTO);
				recived.server.send(recived.socket, this.protocol.createMessage(answer));
			}
		} else {
			Protocol.Message answer = this.protocol.new Message("no", null);
			recived.server.send(recived.socket, this.protocol.createMessage(answer));
		}	
	}

}
